package com.jrx.anytxn.transaction.timer.job.coupon.step;

import com.jrx.anytxn.common.constant.Constants;
import com.jrx.anytxn.common.data.TxnRespCode;
import com.jrx.anytxn.common.exception.TxnBizException;
import com.jrx.anytxn.common.uitl.StringUtils;
import com.jrx.anytxn.customer.entity.CmCustomerRightInfo;
import com.jrx.anytxn.customer.entity.TlCouponDetail;
import com.jrx.anytxn.customer.entity.TlRightsExchangeLog;
import com.jrx.anytxn.customer.service.ICustomerRightService;
import com.jrx.anytxn.customer.service.IRightsExchangeLogService;
import com.jrx.anytxn.customer.service.ITlCouponDetailService;
import com.jrx.anytxn.param.entity.PrActivityInfo;
import com.jrx.anytxn.param.entity.PrRightsAndInterests;
import com.jrx.anytxn.param.service.rights.IPrActivityInfoService;
import com.jrx.anytxn.param.service.rights.IPrRightsAndInterestsService;
import com.jrx.anytxn.transaction.timer.config.CouponConfig;
import com.jrx.anytxn.transaction.timer.job.coupon.dto.CustomerRightsDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.item.ItemWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;

/**
 * ClassName CouponSharingWriter
 *
 * @author lujianyou
 * @version 1.0
 * @description TODO
 * @date 2021/12/24 11:02
 **/
@Service
@Slf4j
public class CouponSharingWriter implements ItemWriter<CustomerRightsDTO> {

    @Autowired
    private ICustomerRightService customerRightService;

    @Autowired
    private ITlCouponDetailService tlCouponDetailService;

    @Autowired
    private IRightsExchangeLogService rightsExchangeLogService;
    @Autowired
    private IPrActivityInfoService activityInfoService;
    @Autowired
    private IPrRightsAndInterestsService rightsAndInterestsService;
    @Autowired
    private CouponConfig couponConfig;

    @Override
    public void write(List<? extends CustomerRightsDTO> items) throws Exception {
        log.info("access into CouponSharingWriter->write()");
        if (items.isEmpty()) {
            return;
        }
        Integer itemsSize = items.size();

        //默认邀新有礼活动
        AtomicReference<String> activityId = new AtomicReference<>(couponConfig.getActivity().getNewUserSharedConsumeFirstActivityId());
        for (int i = 0; i < itemsSize; i++) {
            List<TlCouponDetail> couponDetailList = new ArrayList<>();
            List<CmCustomerRightInfo> customerRightInfoList = new ArrayList<>();
            List<TlRightsExchangeLog> rightsExchangeLogList = new ArrayList<>();

            CustomerRightsDTO item = items.get(i);
            if (item.getCmCustomerRightInfo() != null) {
                customerRightInfoList.add(item.getCmCustomerRightInfo());
                //对特定渠道邀新有礼做特殊处理
                //获取推荐人子渠道
                String subChannel = item.getCmCustomerRightInfo().getSubChannel();
                //获取特定邀新渠道配置
                Map<String, String> specificChannels = couponConfig.getActivity().getSpecificChannelsOfInviteNew();

                if (StringUtils.isNotBlank(subChannel) && !Objects.isNull(specificChannels)) {
                    specificChannels.forEach((key, value) -> {
                        if (key.equals(subChannel)) {
                            activityId.set(value);
                        }
                    });
                }
            }

            if (item.getTlCouponDetail() != null) {
                couponDetailList.add(item.getTlCouponDetail());
            }

            if (item.getRightsExchangeLog() != null) {
                rightsExchangeLogList.add(item.getRightsExchangeLog());
            }

            /**
             * 库存校验
             */
            PrActivityInfo activityInfo = activityInfoService.getByTenantIdAndActivityId(Constants.DEFAULT_TENANT_ID, activityId.get());
            if (activityInfo.getStoreQuantity() < 1) {
                throw new TxnBizException(TxnRespCode.ACTIVITY_STOCK_DEFICIENT);
            }
            PrRightsAndInterests rightsAndInterests = rightsAndInterestsService.getByRightsId(Constants.DEFAULT_TENANT_ID,
                    activityInfo.getRightsId());
            if (rightsAndInterests.getStoreQuantity() < activityInfo.getRightsQuantity()) {
                throw new TxnBizException(TxnRespCode.RIGHTS_AND_INTEREST_STOCK_DEFICIENT);
            }

            if (!customerRightInfoList.isEmpty()) {
                customerRightService.insertBatch(customerRightInfoList);
            }
            if (!couponDetailList.isEmpty()) {
                tlCouponDetailService.insertBatch(couponDetailList);
            }
            if (!rightsExchangeLogList.isEmpty()) {
                rightsExchangeLogService.insertBatch(rightsExchangeLogList);
            }
            // 活动库存扣减
            activityInfo.setStoreQuantity(activityInfo.getStoreQuantity() - 1);
            activityInfo.setUpdateTime(new Date());
            activityInfo.setUpdateBy("batch");
            activityInfoService.updateByPrimaryKeySelective(activityInfo);

            // 权益库存扣减
            rightsAndInterests.setStoreQuantity(rightsAndInterests.getStoreQuantity() - activityInfo.getRightsQuantity());
            rightsAndInterests.setUpdateBy("batch");
            rightsAndInterests.setUpdateTime(new Date());
            rightsAndInterestsService.update(rightsAndInterests);
        }
    }
}
